package org.smart4j.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.helper.ConfigHelper;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 数据库连接工具
 *
 * Created by chinalin on 2017/3/23.
 */
public class DBUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(DBUtil.class) ;

    private static final String driver = ConfigHelper.getJdbcDriver() ;
    private static final String url = ConfigHelper.getJdbcUrl();
    private static final String username = ConfigHelper.getJdbcUsername();
    private static final String password = ConfigHelper.getJdbcPassword();

    //定义一个用于旋转数据库连接的局部线程变量（使每个线程都拥有自己的连接）
    private static ThreadLocal<Connection> connContainer = new ThreadLocal<Connection>() ;

    //获取连接
    public static Connection getConnection(){
        Connection conn = connContainer.get() ;
        try {
            if (conn == null){
                Class.forName(driver);
                conn = DriverManager.getConnection(url,username,password) ;
            }
        }catch (Exception e){
            LOGGER.error("get connection failure " ,e );
            throw new RuntimeException(e) ;
        }finally {
            connContainer.set(conn);
        }
        return conn ;
    }

    //关闭连接
    public static void closeConnection(){
        Connection conn = connContainer.get();
        try {
            if (conn != null){
                conn.close();
            }
        }catch (Exception e){
            LOGGER.error("close connection failure " ,e );
            throw new RuntimeException(e) ;
        }finally {
            connContainer.remove();
        }
    }
}
